﻿using Autofac.Core;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using DFGK_WMS.WebAPI.Controllers.Result;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using static NPOI.HSSF.Util.HSSFColor;

namespace DFGK_WMS.WebAPI.Controllers.RFID
{
    /// <summary>
    /// RFID
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class RFIDController : ControllerBase
    {
        private IRFIDRepository rFIDRepository { get; set; }
        public RFIDController(IRFIDRepository rFIDRepository)
        {
            this.rFIDRepository = rFIDRepository;
        }



        /// <summary>
        /// 导入Excel文件
        /// </summary>
        /// <param name="excelFile"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UploaRFID(IFormFile file)
        {
            try
            {
                // 检查文件是否为空
                if (file == null || file.Length == 0)
                {
                    return Ok(BaseResult.Result("400", "没有选择文件或文件为空"));
                }
                string message = "";
                var postFile = Request.Form.Files[0];
                string extName = Path.GetExtension(postFile.FileName);
                if (!new string[] { ".xls", ".xlsx" }.Contains(extName))
                {
                    return Ok(BaseResult.Result("400", "必须是Excel文件"));
                }
                //string uname = HttpContext.User.FindFirstValue("UserName");
                //int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                MemoryStream ms = new MemoryStream();
                postFile.CopyTo(ms);
                ms.Position = 0;
                IWorkbook wb = null;
                if (extName.ToLower().Equals(".xls")) // 97-2003版本
                {
                    wb = new HSSFWorkbook(ms);
                }

                else
                {
                    wb = new XSSFWorkbook(ms); // 2007以上版本
                }

                ISheet sheet = wb.GetSheetAt(0);

                //总行数（0开始）
                int totalRow = sheet.LastRowNum;
                // 总列数（1开始）
                int totalColumn = sheet.GetRow(0).LastCellNum;
                List<TPriceTags> tPriceTags = new List<TPriceTags>();
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {

                    IRow row = sheet.GetRow(i);
                    if (row == null) continue; // 跳过空行

                    string PriceTagsUrl = "";
                    if (row.GetCell(0)?.CellType == CellType.String)
                    {
                        PriceTagsUrl = row.GetCell(0)?.StringCellValue;
                    }
                    else
                    {
                        PriceTagsUrl = row.GetCell(0)?.NumericCellValue.ToString();
                    }
                    string CellCode = row.GetCell(1)?.StringCellValue;
                    string Sign = row.GetCell(2)?.StringCellValue;
                    string Store_code = "";
                    if (row.GetCell(3)?.CellType == CellType.String)
                    {
                        Store_code = row.GetCell(3)?.StringCellValue;
                    }
                    else
                    {
                        Store_code = row.GetCell(3)?.NumericCellValue.ToString();
                    }

                    var tPriceTag = new TPriceTags
                    {
                       PriceTagsUrl = PriceTagsUrl,
                       CellCode = CellCode,
                       Sign = Sign,
                       Store_code = Store_code
                    };
                    tPriceTags.Add(tPriceTag);
                }
                if (tPriceTags.Count <= 0)
                {
                    //message = "文件信息为空或别写字段为空！";
                    return Ok(BaseResult.Result(false, "导入失败！" + message, "500"));
                }

                var result = rFIDRepository.UpdRFID(tPriceTags);
                wb.Close();

                if (result)
                {
                    return Ok(BaseResult.Result(true, "导入成功！" + message, "200"));
                }
                return Ok(BaseResult.Result(false, "导入失败！", "500"));
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 绑定商品和价签
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult BindMaterialAddRFID(BindMaterialAddRFIDDto task)
        {
            // var data = _service.MESinsertBillData("bee/factoryapi/dts/pick/insertBillData", task);
            var data = rFIDRepository.BindMaterialAddRFID("/api/" + $"{1}" + "/esl/bind", task);

            if (data.error_code == 0)
            {
                return Ok(BaseResult.Result(true, "成功！", "200"));

            }
            return Ok(BaseResult.Result(0, data.error_msg, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
        }

        /// <summary>
        /// 标签点亮
        /// </summary>
        /// <returns></returns>
        #region 暂时不用
        [HttpPost]
        public IActionResult LightUp(List<string> cellCodeList)
        {
            // var data = _service.MESinsertBillData("bee/factoryapi/dts/pick/insertBillData", task);

            var task = rFIDRepository.GetMsgByCellCode(cellCodeList);

            RFIDMsgDto? data = rFIDRepository.LightUp("/api/" + $"{task.sign}" + "esl/sync", task);

            if (data.error_code == 0)
            {
                return Ok(BaseResult.Result(true, "成功！", "200"));
            }
            return Ok(BaseResult.Result(0, data.error_msg, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
        }
        #endregion

        /// <summary>
        /// 巷道灯点亮
        /// </summary>
        /// <param name="cellCode"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult RoadwayLightUp(List<string> cellCode)
        {
            //获取巷道
            var troutwayModel = rFIDRepository.GetTroutway(out string msg,cellCode);

            //获取巷道点亮的参数
            var lightModel = rFIDRepository.GetLightByRoadway(out msg,cellCode,troutwayModel);

            //点亮
            RFIDMsgDto msgDto = rFIDRepository.RoadwayLightUp("api/" + $"{lightModel.sign}" + "/esl/direct", lightModel);

            if (msgDto.error_code != 0)
            {
                return Ok(BaseResult.Result(false, msg, "500"));
            }
            return Ok(BaseResult.Result(true, "成功！", "200"));
        }

        /// <summary>
        /// 巷道灯熄灭
        /// </summary>
        /// <param name="cellCode"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetLightByRoadwayDown(List<string> cellCode)
        {
            //获取巷道
            var troutwayModel = rFIDRepository.GetTroutway(out string msg,cellCode);
            if(troutwayModel == null)
            {
                return Ok(BaseResult.Result(false, msg, "500"));
            }

            //查询巷道灯接口
            var roadwayLightUpDto = rFIDRepository.GetLightByRoadwayDown(out msg,cellCode, troutwayModel);

            //点亮
            RFIDMsgDto msgDto = rFIDRepository.RoadwayLightExtinguish("api/" + $"{roadwayLightUpDto.sign}" + "/esl/direct", roadwayLightUpDto);

            if (msgDto.error_code != 0)
            {
                return Ok(BaseResult.Result(false, msg, "500"));
            }
            return Ok(BaseResult.Result(true, "成功！", "200"));
        }



        /// <summary>
        /// 标签点亮
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult RFIDLightUp(List<string> cellCode)
        {
            var task = rFIDRepository.GetRFIDMsgByCellCode(cellCode);

            //RFIDMsgDto? data = rFIDRepository.RFIDLightUp("api/" + $"{task.store_code}" + "/esl/direct", task);
            RFIDMsgDto? data = rFIDRepository.RFIDLightUp("api/default/esl/direct", task);

            if (data.error_code == 0)
            {
                return Ok(BaseResult.Result(true, "成功！", "200"));
            }
            return Ok(BaseResult.Result(0, data.error_msg, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
        }

        /// <summary>
        /// 标签熄灭
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult RFIDLightDown(List<string> cellCode)
        {
            var task = rFIDRepository.GetRFIDMsgByCellCodeExtinguish(cellCode);

            RFIDMsgDto? data = rFIDRepository.RFIDLightDown("api/default/esl/direct", task);

            if (data.error_code == 0)
            {
                return Ok(BaseResult.Result(true, "成功！", "200"));
            }
            return Ok(BaseResult.Result(0, data.error_msg, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
        }
    }
}
